package demo.uhf.com.androiduhf;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.os.RemoteException;
import android.util.Log;

import com.olc.uhf.UhfAdapter;
import com.olc.uhf.UhfManager;
import com.olc.uhf.tech.ISO1800_6C;
import com.olc.uhf.tech.IUhfCallback;

import java.nio.charset.Charset;
import java.util.List;

import static demo.uhf.com.androiduhf.ByteUtils.stringToBytes;

/**
 * Created by neo on 2017/12/14.
 */

public class UhfHelper {
    private final String TAG = UhfHelper.class.getSimpleName();

    private static final String DATA_START = "*";
    private static final String DATA_END = "#";

    private UhfManager mHhfManager;
    private MyHandler mHandler;
    boolean mIsLooper;
    MyIUhfCallback mUhfCallback;
    ISO1800_6C mIso1800_6C;

    private UhfHelper() {
    }

    private static UhfHelper instance;

    public static UhfHelper getInstance() {
        if (instance == null) {
            instance = new UhfHelper();
        }
        return instance;
    }

    public void init(Context context) {
        mHhfManager = UhfAdapter.getUhfManager(context);
        mIso1800_6C = mHhfManager.getISO1800_6C();
        DevBeep.init(context);
    }

    public boolean isLooper() {
        return mIsLooper;
    }

    public void setLooper(boolean isLooper) {
        this.mIsLooper = isLooper;
    }

    public UhfManager getHhfManager() {
        return mHhfManager;
    }

    public boolean openHuf() {
        return getHhfManager().open();
    }

    public void closeHuf() {
        getHhfManager().close();
    }

    public void startLooper(IUhfListener listener) {
        if (mHandler == null) {
            mHandler = new MyHandler();
        }
        mHandler.setListener(listener);
        mIsLooper = true;
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                while (mIsLooper) {
                    mIso1800_6C.inventory(mUhfCallback = new MyIUhfCallback());
                    if (!mIsLooper) {
                        break;
                    }
                    try {
                        Thread.sleep(150);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                        break;
                    }
                }
            }
        });
        thread.start();
    }

    public void stopLooper() {
        setLooper(false);
    }

    public String getEpcData(String epc) {
        String data = ByteUtils.hexStringToString(epc);
        if (data.contains(DATA_START) && data.contains(DATA_END)) {
            int startIndex = data.indexOf(DATA_START);
            int endIndex = data.indexOf(DATA_END);
            return data.substring(startIndex + 1, endIndex);
        }
        return "";
    }

    public int write(String pwd, String epc, Byte btMemBank, int startIndex
            , int dataLen, String data) {
        //密码
        byte[] pwdByte = stringToBytes(pwd);

        //epc长度
        byte[] epcByte = stringToBytes(epc);

        //btMemBank 区块 user区等

        //起始地址 startIndex
        int nadd = Integer.valueOf(startIndex);

//        byte[] pwrite = new byte[length * 2];


//        byte[] myByte = stringToBytes(data);
        //拼接自己的结尾符
        data = DATA_START + data + DATA_END;
        //数据读取长度
        int length = 13;

        byte[] myByte = data.getBytes(Charset.forName("UTF-8"));
//        System.arraycopy(myByte, 0, pwrite, 0,
//                myByte.length > dataLen * 2 ? dataLen * 2 : myByte.length);

        int isWrite = mIso1800_6C.write(pwdByte, epcByte.length, epcByte,
                btMemBank, (byte) nadd, length, myByte);
        return isWrite;
    }


    /**
     * 接收轮询回调
     */
    class MyIUhfCallback extends IUhfCallback.Stub {

        @Override
        public void doInventory(List<String> list) throws RemoteException {
            //获取数据
            for (int i = 0; i < list.size(); i++) {
                String strepc = list.get(i);
                Log.d(TAG, "doInventory =" + strepc);
                Log.d(TAG, "RSSI=" + strepc.substring(0, 2));
                Log.d(TAG, "PC=" + strepc.substring(2, 6));
                Log.d(TAG, "EPC=" + strepc.substring(6));

                String epc = strepc.substring(6);

                DevBeep.PlayOK();
                String strEpc = strepc.substring(2, 6) + epc;

                Log.d(TAG, "16进制转String =" + ByteUtils.hexStringToString(epc));

                Message msg = new Message();
                msg.what = 1;
                msg.obj = strEpc;
                mHandler.sendMessage(msg);
            }
        }

        @Override
        public void doTIDAndEPC(List<String> list) throws RemoteException {
            //获取数据
            for (int i = 0; i < list.size(); i++) {
                String strepc = list.get(i);
                Log.d(TAG, "doTIDAndEPC =" + strepc);
            }
        }
    }


    /**
     * 接收发送的消息
     */
    private static class MyHandler extends Handler {
        IUhfListener weakReference;

        public void setListener(IUhfListener listener) {
            this.weakReference = listener;
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    String data = (String) msg.obj;
                    if (weakReference != null) {
                        weakReference.doInventory(data);
                    }
                    break;
            }
        }
    }

    /**
     * 轮询回调监听
     */
    public interface IUhfListener {
        void doInventory(String data);
    }

}
